<template>
  <div class="chart-container">
    <div ref="chartRef" style="width: 100%; height: 400px"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  data: {
    type: Array,
    default: () => []
  }
})

const chartRef = ref(null)
let chartInstance = null

const initChart = () => {
  const option = {
    title: {
      text: '答题用户排行',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: props.data.map(item => item.nickname),
      axisLabel: {
        rotate: 45,
        formatter: (value) => {
          return value.length > 6 ? value.substring(0,6)+'...' : value
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '答题次数'
    },
    series: [{
      data: props.data.map(item => item.count),
      type: 'bar',
      itemStyle: {
        color: '#5B8FF9'
      }
    }]
  }

  chartInstance.setOption(option)
}

onMounted(() => {
  chartInstance = echarts.init(chartRef.value)
  window.addEventListener('resize', () => chartInstance.resize())
  initChart()
})

watch(() => props.data, () => {
  initChart()
})
</script>
